package com.geoclient.rest.infra.uri;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @author Gmaps / Soliva
 * 
 */
public final class InfraGeoGoogle {
	private static String keyString = "MY_API_KEY";
	private static byte[] key;

	public static String createResource(String urlString) {
		URL url = null;
		try {
			url = new URL(urlString);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		InfraGeoGoogle signer = null;
		try {
			signer = new InfraGeoGoogle(keyString);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String request = null;
		try {
			request = signer.signRequest(url.getPath(), url.getQuery());
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		request = 	url.getProtocol().concat("://").concat(url.getHost()).concat(request);
		return request;

	}

	private InfraGeoGoogle(String keyString) throws IOException {
		keyString = keyString.replace('-', '+');
		keyString = keyString.replace('_', '/');
		System.out.println("Key: " + keyString);
		this.key = Base64.decode(keyString);
	}

	private String signRequest(String path, String query)
			throws NoSuchAlgorithmException, InvalidKeyException,
			UnsupportedEncodingException, URISyntaxException {
		String resource = path + '?' + query;
		SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1");
		Mac mac = Mac.getInstance("HmacSHA1");
		mac.init(sha1Key);
		byte[] sigBytes = mac.doFinal(resource.getBytes());
		String signature = Base64.encodeBytes(sigBytes);
		signature = signature.replace('+', '-');
		signature = signature.replace('/', '_');
		return resource + "&signature=" + signature;
	}

}